package com.mezz.bones.bff.app.adapter.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.mezz.bones.framework.base.domain.response.Result;
import com.mezz.bones.framework.id.generator.service.IDistributedIdGeneratorService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: zhuang
 * @Date: 2024/8/30 19:02
 * @Description: TODO
 * @Version: 1.0
 **/

@RestController
@RequestMapping("/hello")
@SaIgnore
@Api("测试项目启动")
@Slf4j
public class HelloController {

    @Resource
    private IDistributedIdGeneratorService distributedIdGeneratorService;

    @GetMapping
    public Result<?> helloWorld() {

        // 创建固定大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        // 使用 CountDownLatch 确保所有线程执行完毕
        CountDownLatch latch = new CountDownLatch(100);
        // 用于存储生成的 ID
        Set<Long> generatedIds = Collections.synchronizedSet(new HashSet<>());

        for (int i = 0; i < 100; i++) {
            executorService.submit(() -> {
                try {
                    long id = distributedIdGeneratorService.getNextId("test");
                    // 使用日志记录 ID
                    log.info("Generated ID: {}", id);
                    generatedIds.add(id);
                } catch (Exception e) {
                    // 记录异常信息
                    log.error("Error generating ID", e);
                } finally {
                    // 线程执行完毕，计数器减一
                    latch.countDown();
                }
            });
        }

        try {
            // 等待所有线程执行完毕
            latch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            // 记录中断异常信息
            log.error("Thread interrupted while waiting for all tasks to complete", e);
            // 抛出专用异常
            throw new IdGenerationTestException("Thread interrupted during ID generation test", e);
        } finally {
            // 关闭线程池
            executorService.shutdown();
        }

        System.out.println("All IDs generated: " + generatedIds.size());
        return Result.OK("helloWorld");
    }

    /**
     * 自定义异常类，用于 ID 生成测试过程中的异常
     */
    private static class IdGenerationTestException extends RuntimeException {
        public IdGenerationTestException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}
